import React, { useState } from "react";
import {
  Box,
  Typography,
  TextField,
  Button,
  Rating,
  Card,
  CardContent,
  IconButton,
  Grid
} from "@mui/material";
import { Add, Delete } from "@mui/icons-material";
import { ThemeProvider, CssBaseline } from "@mui/material";
import theme from "../themes/theme ";
import { useNavigate } from "react-router-dom";

interface Dimension {
  id: number;
  name: string;
  score: number | null;
}

const NewSurvey: React.FC = () => {
  const [title, setTitle] = useState("");
  const [dimensions, setDimensions] = useState<Dimension[]>([
    { id: 1, name: "准确性", score: null },
    { id: 2, name: "稳定性", score: null },
    { id: 3, name: "可扩展性", score: null },
    { id: 4, name: "可解释性", score: null }
  ]);

  const navigate = useNavigate();

  const handleDimensionChange = (id: number, key: "name" | "score", value: any) => {
    setDimensions((prev) =>
      prev.map((dim) =>
        dim.id === id ? { ...dim, [key]: value } : dim
      )
    );
  };

  const addDimension = () => {
    const newId = dimensions.length > 0 ? Math.max(...dimensions.map((d) => d.id)) + 1 : 1;
    setDimensions([...dimensions, { id: newId, name: "", score: null }]);
  };

  const removeDimension = (id: number) => {
    setDimensions((prev) => prev.filter((dim) => dim.id !== id));
  };

  const handleSubmit = () => {
    if (!title.trim()) {
      alert("问卷标题不能为空");
      return;
    }

    const newSurvey = {
      id: Date.now(),
      title,
      dimensions,
      createdAt: new Date().toISOString().split("T")[0]
    };

    const existing = localStorage.getItem("surveys");
    const surveyList = existing ? JSON.parse(existing) : [];
    surveyList.push(newSurvey);
    localStorage.setItem("surveys", JSON.stringify(surveyList));

    navigate("/surveyStatistics"); // 页面跳转到统计页
  };

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Box p={4}>
        <Typography variant="h4" gutterBottom>
          新建模型评估问卷
        </Typography>

        <Box mb={3}>
          <TextField
            fullWidth
            label="问卷标题"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
        </Box>

        <Box mb={2}>
          <Typography variant="h6">维度评分项</Typography>
          {dimensions.map((dim) => (
            <Card key={dim.id} sx={{ mb: 2 }}>
              <CardContent>
                <Grid container spacing={2} alignItems="center">
                  <Grid item xs={5}>
                    <TextField
                      fullWidth
                      label="维度名称"
                      value={dim.name}
                      onChange={(e) =>
                        handleDimensionChange(dim.id, "name", e.target.value)
                      }
                    />
                  </Grid>
                  <Grid item xs={5}>
                    <Rating
                      value={dim.score}
                      onChange={(_, newValue) =>
                        handleDimensionChange(dim.id, "score", newValue)
                      }
                    />
                  </Grid>
                  <Grid item xs={2}>
                    <IconButton onClick={() => removeDimension(dim.id)} color="error">
                      <Delete />
                    </IconButton>
                  </Grid>
                </Grid>
              </CardContent>
            </Card>
          ))}

          <Button
            variant="outlined"
            startIcon={<Add />}
            onClick={addDimension}
            sx={{ mt: 1 }}
          >
            添加评分维度
          </Button>
        </Box>

        <Button variant="contained" color="primary" onClick={handleSubmit}>
          提交问卷
        </Button>
      </Box>
    </ThemeProvider>
  );
};

export default NewSurvey;
